<template>
  <div class="user-management-container">
    <h2>用户管理</h2>
    <div class="toolbar">
      <app-search @search="performSearch" placeholder="按用户名搜索" />
      <el-button type="primary" @click="openUserDialog()">添加用户</el-button>
    </div>
    <el-table :data="data" v-loading="loading">
      <el-table-column prop="reader_id" label="ID" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="role" label="角色" />
      <el-table-column label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" @click="openUserDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <app-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @update:current-page="handlePageChange"
      @update:page-size="handleSizeChange"
    />

    <el-dialog v-model="userDialogVisible" :title="isEditMode ? '编辑用户' : '添加用户'">
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditMode">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role">
            <el-option label="Reader" value="reader" />
            <el-option label="Author" value="author" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useCRUD } from '@/composables/useCRUD'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppSearch from '@/components/AppSearch.vue'
import AppPagination from '@/components/AppPagination.vue'
import { ADMIN_API } from '@/utils/api'

// 假设获取用户的API是 /admin/users
const { 
  data, 
  loading, 
  pagination, 
  fetchData, 
  handleSearch, 
  handlePageChange, 
  handleSizeChange 
} = useCRUD(`${ADMIN_API}/users`)

const userDialogVisible = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  reader_id: null,
  username: '',
  password: '',
  role: 'reader'
})

const isEditMode = computed(() => !!userForm.reader_id)

const userFormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const performSearch = (query) => {
  handleSearch({ q: query })
}

const openUserDialog = (user) => {
  if (user) {
    // Edit mode
    Object.assign(userForm, user)
    userForm.reader_id = user.reader_id
  } else {
    // Create mode
    Object.assign(userForm, { reader_id: null, username: '', password: '', role: 'reader' })
  }
  userDialogVisible.value = true
}

const saveUser = async () => {
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEditMode.value) {
          await request.put(`${ADMIN_API}/users/${userForm.reader_id}`, userForm)
          ElMessage.success('用户更新成功')
        } else {
          await request.post(`${ADMIN_API}/users`, userForm)
          ElMessage.success('用户创建成功')
        }
        userDialogVisible.value = false
        fetchData() // 重新加载数据
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

const toggleUserStatus = async (user) => {
  const newStatus = user.status === 'active' ? 'disabled' : 'active'
  try {
    await request.patch(`${ADMIN_API}/users/${user.reader_id}/status`, { status: newStatus })
    ElMessage.success('状态更新成功')
    fetchData()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

const deleteUser = async (user) => {
  ElMessageBox.confirm('确定要永久删除该用户吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`${ADMIN_API}/users/${user.reader_id}`)
      ElMessage.success('用户删除成功')
      fetchData() // 重新加载数据
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>